const fs = require("fs");
const path = require("path");
const router = require("../router");
const {
    params,
    route
} = require("../router");
const dbPath = path.join("C:/Users/张君艳/Desktop/zjy103zy/app/db", "./file.json");
// 文件增
const fileAddService = async (params) => {
    // 读取文件
    const myData = await JSON.parse(fs.readFileSync(dbPath, "utf-8"));
    myData.push(params);
    // 写入文件
    await fs.writeFileSync(dbPath, JSON.stringify(myData), "utf-8");
    return true;
}
// 文件查
const fileselectService = async (params) => {
    // 读取文件
    const myData = await JSON.parse(fs.readFileSync(dbPath, "utf-8"));
    return myData;
}
// 文件删
const filedeleteService = async (params) => {
    // 读取文件
    const myData = await JSON.parse(fs.readFileSync(dbPath, "utf-8"));
    const arr = [];
    //循环
    await myData.forEach(item => {
        // 把和传过来和id不符合的添加到arr
        if (item.id != params) {
            arr.push(item);
        }
    });
    // 写入文件
    await fs.writeFileSync(dbPath, JSON.stringify(arr), "utf-8");
    return true;
}
// 文件改
const fileupdataService = async (params) => {
     // 读取文件
     const myData = await JSON.parse(fs.readFileSync(dbPath, "utf-8"));
    //  const arr = [];
     
     const fileters = await myData.filters(v=>{
        return v.id==id;
     })
     console.log(fileters);
     if(fileters[0]){
        fileters[0].username = params.username;
        fileters[0].password = params.password;
        fileters[0].nickname = params.nickname;
        fileters[0].age = params.age;
        fileters[0].phone = params.phone;
     }
     // 写入文件
     await fs.writeFileSync(dbPath, JSON.stringify(fileters), "utf-8");
     return true;
}
module.exports = {
    fileAddService,
    fileselectService,
    filedeleteService,
    fileupdataService,
}